package com.csg.boot.starter.config;

import com.csg.boot.starter.builder.DocketBuilder;
import com.csg.boot.starter.builder.UiConfigurationBuilder;
import com.csg.boot.starter.constant.SwaggerProperties;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.UiConfiguration;

import java.util.LinkedList;
import java.util.List;

/**
 * @author george
 */
@Configuration
public class SwaggerConfig implements BeanFactoryAware {

    private static DocketBuilder docketBuilder = DocketBuilder.getInstance();
    private static UiConfigurationBuilder uiConfigurationBuilder = UiConfigurationBuilder.getInstance();
    private BeanFactory beanFactory;
    @Autowired
    private SwaggerProperties properties;

    @Bean
    public UiConfiguration uiConfiguration() {
        return uiConfigurationBuilder.build(properties.getUiConfig());
    }

    @Bean
    public List<Docket> dockets() {
        List<Docket> dockets = new LinkedList<>();
        properties.getDockets().put(properties.getDocket().getGroupName(), properties.getDocket());
        properties.getDockets().forEach((key, value) -> {
            Docket docket = docketBuilder.build(value);
            ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
            configurableBeanFactory.registerSingleton(key, docket);
            dockets.add(docket);
        });
        return dockets;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }
}
